<template>
  <div>
    <basic-layout title="商品订单" :isDefaultHeader="true" :showAddBtn="false">
      <template #defaultHeader>
        <van-row class="search-row" style="background: #4eb3e9">
          <van-search
            v-model="formData.keyword"
            shape="round"
            maxlength="20"
            background="transparent"
            placeholder="订单编号 / 商品名称"
            @search="onRefresh"
          />
          <van-icon name="filter-o" @click="$refs.queryPopupRef.show = true" />
        </van-row>
      </template>
      <div class="columnFlex">
        <van-tabs v-model="curTabName" @click="onRefresh">
          <van-tab v-for="(val, i) in tabsList" :key="i" :title="val.label">
          </van-tab>
        </van-tabs>
        <van-row class="listCon">
          <van-list
            class="orderList"
            v-model="refreshLoading"
            :finished="finished"
            :finished-text="listData.length ? '没有更多了' : ''"
            @load="onLoad"
          >
            <div class="orderBox" v-for="item in listData" :key="item.orderNo">
              <div @click="handleDeail(item.orderNo)">
                <div class="active">
                  <p style="display: flex; align-items: center">
                    <van-icon
                      name="shop-o"
                      size="20px"
                      style="margin-right: 10px"
                    /><span>{{ item.networkName }}</span>
                  </p>
                  <div style="flex: 1; text-align: right; color: #ee0a24">
                    {{ item.orderStatusLabel }}
                  </div>
                </div>
                <div
                  class="cardBox"
                  v-for="val in item.orderGoodsVOS"
                  :key="val.goodsId"
                >
                  <div style="display: flex">
                    <a class="left">
                      <img
                        :src="
                          fileUrlObj[val.goodsMainFileCode] ||
                          (loading ? 'loading.gif' : 'noImgData.png')
                        "
                      />
                    </a>
                    <div class="right">
                      <div class="righTxt">
                        <p class="handTxt">
                          {{ val.goodsName }}
                        </p>
                        <p class="specs">{{ val.attrNames }}</p>
                      </div>
                      <div style="text-align: right; flex: none">
                        <p style="margin-top: 2px">¥{{ val.sellingPrice }}</p>
                        <p class="specs">x{{ val.buyCount }}</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div
                class="roundBox"
                v-if="item.afterSalesStatus != 1 && item.refundAmount != null"
              >
                <span
                  >退款金额：¥{{
                    item.refundAmount == null ? 0 : item.refundAmount
                  }}</span
                >
                <span
                  :class="item.afterSalesStatus == 2 ? 'redTxt' : ''"
                  style="margin-left: 20px"
                  >{{ item.afterSalesStatusLabel }}</span
                >
              </div>
              <div class="spanBox">
                <van-button
                  round
                  plain
                  hairline
                  type="default"
                  v-if="item.orderStatus == 1"
                  @click="handleClose(item)"
                  >取消订单</van-button
                >
                <van-button
                  round
                  plain
                  hairline
                  type="default"
                  style="margin-left: 10px"
                  v-if="item.orderStatus == 4 && item.commentStatus == 2"
                  @click="appraise(item)"
                  >评价</van-button
                >
                <van-button
                  round
                  plain
                  hairline
                  type="default"
                  style="margin-left: 10px"
                  v-if="item.orderStatus == 5"
                  @click="handleDelete(item)"
                  >删除订单</van-button
                >
                <van-button
                  round
                  type="primary"
                  class="success"
                  v-if="item.orderStatus == 3"
                  @click="handleReceipt(item)"
                  >确认收货</van-button
                >

                <van-button
                  round
                  type="danger"
                  class="success"
                  style="margin-left: 10px"
                  v-if="item.afterSalesStatus === '1' && item.orderStatus == 4"
                  @click="handleUpdRefund(item)"
                  >申请退款</van-button
                >

                <van-button
                  round
                  type="danger"
                  class="success"
                  style="margin-left: 10px"
                  v-if="item.afterSalesStatus === '2' && item.orderStatus == 4"
                  @click="handleUpdRefund(item)"
                  >修改退款</van-button
                >
              </div>
            </div>
          </van-list>
          <van-empty
            v-if="!spinLoading && !listData.length"
            class="custom-image"
            :image="require('../../../../assets/images/empty.png')"
            description="暂无数据"
          />
        </van-row>
      </div>
    </basic-layout>
    <full-loading v-if="spinLoading"></full-loading>
    <!-- 筛选条件弹出框 -->
    <queryPopup
      ref="queryPopupRef"
      @handleSearch="onRefresh"
      @handleReset="handleReset"
    >
      <van-form class="filterBox">
        <label>订单日期</label>
        <van-field>
          <template #input>
            <div class="textCon" @click="showTimePicker = true">
              <span v-if="!formData.beginDate" style="color: #aaa"
                >请选择订单日期</span
              >
              <span v-else
                >{{ formData.beginDate }} ~ {{ formData.endDate }}</span
              >
            </div>
          </template>
          <template #button>
            <van-icon
              v-if="formData.beginDate"
              name="cross"
              @click="clearPicker('date')"
            />
          </template>
        </van-field>
      </van-form>
    </queryPopup>
    <!-- 订单日期 -->
    <van-calendar
      v-model="showTimePicker"
      :min-date="minDate"
      :max-date="maxDate"
      :allow-same-day="true"
      type="range"
      @confirm="onTimeConfirm"
    />
    <!-- 取消原因 -->
    <van-dialog
      v-model="showCancelModal"
      title="取消原因"
      show-cancel-button
      :beforeClose="handleSure"
    >
      <van-field
        v-model="cancelFormData.cancelReason"
        rows="5"
        type="textarea"
        maxlength="256"
        placeholder="请输入取消原因"
        show-word-limit
      />
    </van-dialog>
    <!-- 新增/详情/编辑 弹出框 -->
    <modeal
      :showModal="fullscreenModal"
      @handleClose="fullscreenModal = false"
      @refresh="onRefresh"
      ref="modealRef"
    />
    <!-- 评价 -->
    <fullscreenModal
      :modal="assessModal"
      label="订单评价"
      :isShowEdit="false"
      :showSave="false"
      editType="other"
      @handleClose="assessModal = false"
    >
      <evaluate
        @close="assessModal = false"
        @refresh="onRefresh()"
        ref="evaluateRef"
      />
    </fullscreenModal>
    <!-- 退款 -->
    <fullscreenModal
      :modal="showUpdRefundModal"
      :label="text"
      :isShowEdit="false"
      editType="other"
      @handleClose="showUpdRefundModal = false"
      @handleSave="$refs.refundFormRef.handleUpdRefundSure()"
    >
      <refundForm
        @close="showUpdRefundModal = false"
        @refresh="onRefresh"
        ref="refundFormRef"
      />
    </fullscreenModal>
  </div>
</template>

<script>
import { queryFileList } from "@/api/common";
import modeal from "./orderStatus";
import refundForm from "./refundForm";
import evaluate from "../goodsAppraise/evaluate";
import {
  orderPage,
  cancelOrder,
  delOrder,
  takeOrder,
} from "@/api/srvAssurance/shoppingMall/order";

export default {
  components: { modeal, refundForm, evaluate },

  data() {
    return {
      loading: false,
      refreshLoading: false,
      spinLoading: false,
      finished: false,
      showCancelModal: false,
      fullscreenModal: false,
      showUpdRefundModal: false,
      showPicker: false,
      showTimePicker: false,
      assessModal: false,
      formData: {
        keyword: "",
        orderQueryStatus: "",
        beginDate: "",
        endDate: "",
        pageNum: 1,
        pageSize: 10,
      },
      tabsList: [
        { name: "0", label: "全部" },
        { name: "1", label: "待付款" },
        { name: "2", label: "待发货" },
        { name: "3", label: "待收货" },
        { name: "4", label: "待评价" },
        { name: "5", label: "退款/售后" },
      ],
      minDate: new Date(new Date().getFullYear() - 1, 0, 1),
      maxDate: new Date(),
      text: "",
      curTabName: "0",
      currentPage: 1,
      listData: [],
      fileUrlObj: {},
      cancelFormData: {
        orderNo: "",
        cancelReason: "",
      },
    };
  },
  mounted() {
    this.getSearch();
  },
  methods: {
    getSearch() {
      if (
        this.formData.keyword &&
        !this.$commonReg.textReg.test(this.formData.keyword)
      ) {
        this.$Notify({
          type: "warning",
          message: `关键字${this.$commonReg.textMsg}`,
        });
        return;
      }
      let params = {
        keyword: this.formData.keyword || "",
        orderQueryStatus: this.curTabName == "0" ? "" : this.curTabName,
        beginDate:
          this.formData.beginDate != ""
            ? this.formData.beginDate + " 00:00:00"
            : "",
        endDate:
          this.formData.endDate != ""
            ? this.formData.endDate + " 00:00:00"
            : "",
        pageNum: this.currentPage,
        pageSize: 10,
      };
      let fileCodeArr = [];
      this.spinLoading = true;
      orderPage(params)
        .then((res) => {
          if (res.code == 1000 && res.data) {
            this.listData = [...this.listData, ...res.data.records];
            res.data.records.forEach((item, i) => {
              item.orderGoodsVOS.forEach((val) => {
                if (
                  val.goodsMainFileCode &&
                  !this.fileUrlObj[val.goodsMainFileCode]
                ) {
                  fileCodeArr.push(val.goodsMainFileCode);
                  this.fileUrlObj[val.goodsMainFileCode] = "";
                }
              });
            });
            if (fileCodeArr.length) {
              this.queryFileInfoData(fileCodeArr);
            }

            if (this.listData.length >= res.data.total) {
              this.finished = true;
            }
          }
          setTimeout(() => {
            this.spinLoading = false;
          }, 400);
        })
        .catch(() => {
          this.spinLoading = false;
          this.finished = true;
        });
    },
    onRefresh() {
      this.refreshLoading = false;
      this.finished = false;
      this.listData = [];
      this.currentPage = 1;
      this.getSearch();
    },
    onLoad() {
      this.currentPage++;
      this.getSearch();
    },
    // 删除订单
    handleDelete(item) {
      this.$Dialog
        .confirm({
          title: "是否确定删除该订单？",
        })
        .then(() => {
          this.spinLoading = true;
          delOrder(item.orderNo)
            .then((res) => {
              this.spinLoading = false;
              if (res.code === 1000) {
                this.$Notify({ type: "success", message: "删除成功！" });
                this.onRefresh();
              }
            })
            .catch(() => {
              this.spinLoading = false;
            });
        })
        .catch(() => {});
    },
    // 获取图片信息
    queryFileInfoData(fileCodeArr) {
      this.loading = true;
      queryFileList(fileCodeArr)
        .then((res) => {
          if (res.code === 1000 && res.data) {
            res.data.forEach((item) => {
              this.fileUrlObj[item.fileCode] = item.url;
            });
            this.$forceUpdate();
            this.loading = false;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 订单日期选择
    onTimeConfirm(date) {
      const [start, end] = date;
      this.formData.beginDate = new Date(start).format("yyyy-MM-dd");
      this.formData.endDate = new Date(end).format("yyyy-MM-dd");
      this.showTimePicker = false;
      this.onRefresh();
    },
    // 清空查询条件
    clearPicker(type) {
      this.formData.beginDate = "";
      this.formData.endDate = "";
      this.onRefresh();
    },
    // 重置
    handleReset() {
      this.formData = {
        keyword: "",
        orderQueryStatus: "",
        beginDate: "",
        endDate: "",
        pageNum: 1,
        pageSize: 10,
      };
      this.text = "";
      this.onRefresh();
    },
    handleClose(item) {
      this.cancelFormData.cancelReason = "";
      this.cancelFormData.orderNo = item.orderNo;
      this.showCancelModal = true;
    },
    appraise(item) {
      this.assessModal = true;
      this.$refs.evaluateRef.resetForm();
      this.$refs.evaluateRef.getData(item);
    },
    // 确认收货
    handleReceipt(item) {
      this.$Dialog
        .confirm({
          title: "是否确定确认收货？",
        })
        .then(() => {
          this.spinLoading = true;
          takeOrder(item.orderNo)
            .then((res) => {
              this.spinLoading = false;
              if (res.code === 1000) {
                this.$Notify({ type: "success", message: "确认收货成功！" });
                this.onRefresh();
              }
            })
            .catch(() => {
              this.spinLoading = false;
            });
        })
        .catch(() => {});
    },
    // 退款
    handleUpdRefund(item) {
      this.spinLoading = true;
      this.text = item.afterSalesStatus === "2" ? "修改退款信息" : "申请退款";
      this.$refs.refundFormRef.getOrderData(item);
      this.showUpdRefundModal = true;
      setTimeout((_) => {
        this.spinLoading = false;
      }, 500);
    },

    handleDeail(item) {
      this.$refs.modealRef.handleOpen(item);
      this.fullscreenModal = true;
    },
    // 确定取消
    handleSure(action, done) {
      if (action === "confirm") {
        done(false);
        if (!this.cancelFormData.cancelReason) {
          this.$Notify({ type: "warning", message: "请输入取消原因" });
          return;
        }
        this.fullLoading = true;
        cancelOrder(this.cancelFormData)
          .then((res) => {
            this.fullLoading = false;
            if (res.code === 1000) {
              this.showCancelModal = false;
              this.$Notify({ type: "success", message: "取消成功！" });
              this.onRefresh();
            }
          })
          .catch(() => {
            this.fullLoading = false;
          });
      } else {
        done();
      }
    },
  },
};
</script>

<style scoped lang="less">
/deep/.van-nav-bar__content {
  background: #1e93ff;
  .van-nav-bar__title {
    color: #fff;
  }
}
/deep/ .van-tabs__line {
  background-color: #009c84;
}

.listCon {
  padding: 0;
}
.search-row {
  align-items: center;
  .van-icon {
    font-size: 20px;
    color: #fff;
    margin-right: 13px;
  }
}
.orderBox {
  margin-top: 10px;
  box-sizing: border-box;
  border-radius: 10px;
}
.orderList {
  padding: 8px;
  box-sizing: border-box;
}
.active {
  display: flex;
  padding: 10px;
  align-items: center;
  background: #fff;
}
img {
  width: 100%;
  height: 100%;
}
.cardBox {
  padding: 8px;
  font-size: 14px;
  color: #323233;
  box-sizing: border-box;
  background-color: #fff;
  .left {
    width: 80px;
    height: 70px;
    flex: none;
    margin-right: 8px;
  }
  .right {
    display: flex;
    flex: 1px;
    .righTxt {
      flex: 1;
      .handTxt {
        width: 189px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .specs {
      color: #7f7f7f;
      font-size: 12px;
      margin-top: 5px;
    }
  }
}
.spanBox {
  display: flex;
  justify-content: flex-end;
  background: #fff;
  padding-bottom: 10px;
  padding-right: 5px;
  button {
    width: 85px;
    height: 30px;
    font-size: 12px;
  }
  /deep/ .van-button--default {
    border: 0.02667rem solid #ccc;
  }
}
.roundBox {
  background: #fff;
  padding: 10px;
  .redTxt {
    color: #ee0a24;
  }
}
</style>
